﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL_NhaSach;
using BLL;

namespace BLL_NhaSach
{
	public class SachBLL : IProcessData
	{
		QLNhaSachEntities db;

		public SachBLL(string cnStr)
		{
			db = new QLNhaSachEntities(cnStr);
		}

		public object getAllData()
		{
			return (from tl in db.TheLoais join s in db.Saches on tl.MaLoai equals s.MaLoai select new { s.MaSach, s.TenSach, s.TacGia, s.GiaBia, s.SoLuongTon, tl.TenLoai });
		}

		public object findObjects(string find_content)
		{
			return (db.Saches.SingleOrDefault(p => p.MaSach.Equals(find_content)));
		}

		public object findObjects(int find_content)
		{
			throw new NotImplementedException();
		}

		public object sort(string Col_Name, bool state)
		{
			throw new NotImplementedException();
		}

		public bool addObject(object addObj)
		{
			Sach s = (Sach)addObj;
			if (s != null)
			{
				try
				{
					db.Saches.AddObject(s);
					db.SaveChanges();
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}
			else return false;
		}

		public bool deleteObject(int id)
		{
			throw new NotImplementedException();
		}
		public bool deleteObject(String id)
		{
			Sach s = db.Saches.SingleOrDefault(p => p.MaSach.Equals(id));
			if (s == null)
			{
				return false;
			}
			else
			{
				try
				{
					db.Saches.DeleteObject(s);
					db.SaveChanges();
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}
		}
		public bool updateObject(object updateObj)
		{
            Sach sach = (Sach)updateObj;
            Sach sach_old = db.Saches.SingleOrDefault(p => p.MaSach.Equals(sach.MaSach));
            if (sach_old != null)
            {
                sach_old.TenSach = sach.TenSach;
                sach_old.SoLuongTon = sach.SoLuongTon;
                sach_old.TacGia = sach.TacGia;
                sach_old.MaLoai = sach.MaLoai;
                sach_old.GiaBia = sach.GiaBia;
                try
                {
                    db.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else return false;

		}
	}
}
